'''
Created on 2014-2-4

@author: apple
'''
from django.utils.translation import ugettext_lazy as _
from common import *
from com.ad.sword.service.SystemConfigService import *
from com.ad.sword.dao.models import User
from com.ad.sword.web import settings




def index(request):
    return template("login.html")



def login(request):
    def password_md5(user):
        import hashlib
 
        m = hashlib.md5()
        m.update(request.session.session_key)
        m.update(":")
        m.update(user.password)
 
        return m.hexdigest()
 
    try:
        user = User.objects.get(username = get_required_argument(request, 'username'))
    except DoesNotExist:
        return template("login.html", error_msg(msg=_("Account does not exist")))
 
#     if user.locked and user.unlock_time > datetime.now():
#         return error_msg(msg=_("Account locked"))
 
    if get_required_argument(request, 'password') != user.password:
#         user.retry_count = user.retry_count + 1
#         limit = 5
#         try:
#             sc = SystemConfigService.getByName('login_fail_times')
#             limit = int(sc)
#             if not limit:
#                 limit = 5
#         except:
#             pass
#          
#         if user.retry_count >= limit:
#             user.locked = True
#             user.unlock_time = datetime.now() + timedelta(0, 3600)
#             user.save()
#             request.log.Warning(title=_("Account locked"))
#             return error_msg(msg=_("Account locked"))
#         else:
#             user.save()
#             return error_msg(msg=_("Invalid password"))
        return template("login.html",error_msg(msg=_("Invalid password")))
    else:
        request.session['user_id'] = user.id
        request.session['username'] = user.username
 
        user.last_login_time = datetime.now()
        user.save()
 
        request.log.Info(title="Log in")
        return template("main.html",{"userId":user.id})



def logout(request):
    request.log.Info(title=_("Log out"))
    request.session.clear()
    return template("login.html")
